<?php
namespace Admin\Model;

use Common\Model\CommonModel;

class SaleManagerBillModel extends CommonModel {

    /**
     * 账单列表
     */
    public function get_list($where = array(),$order = '',$from =  0,$to = 0)
    {
        $list = M("SaleManagerBill")->alias("b")->field("b.*,sm.sale_manage_name,u.user_nicename,u.user_phone")->where($where)
            ->join("bdt_sale_manager sm ON sm.id = b.sale_manager_id","LEFT")
            ->join("bdt_users u ON u.id = b.admin_id","LEFT")
            ->order($order)
            ->limit($from, $to)
            ->select();
        return $list;
    }
    /**
     * @param $sale_manager_id
     * @param $price
     * @param $model 1账户充值 2退款金额
     */
    public function insert_data($sale_manager_id, $price, $model){
       $add_price_model = array(1);
       $reduce_price_model = array(2);
        if(!in_array($model,$add_price_model) && !in_array($model,$reduce_price_model)){
            return -1;
        }
        $insert = array(
            'sale_manager_id'=>$sale_manager_id,
            'model' =>  $model,
            'admin_id'=>session('ADMIN_ID'),
        );
        if(in_array($model,$reduce_price_model)){
            $price = -$price;
        }
        $insert['price'] = $price;
        $insert['create_time'] = time();

        $sale_manager = M("SaleManager")->where(array("id"=>$sale_manager_id))->find();
        if(empty($sale_manager)){
            return -2;
        }

        $cur_balance = round($sale_manager['balance']+($price),2);
        $insert['balance'] = $cur_balance;
        $result = $this->add($insert);
        
        if($result){
            M("SaleManager")->where(array("id"=>$sale_manager_id))->save(array("balance"=>$cur_balance));
            return true;
        }else{
            return false;
        }

    }
}